package com.alander.nexusgo.im.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 在线状态服务类
 */
@Service
public class OnlineService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String ONLINE_PREFIX = "nexusgo:im:online:";

    /**
     * 判断用户是否在线
     *
     * @param userId 用户ID
     * @param appId  应用ID
     * @return 是否在线
     */
    public boolean isOnline(long userId, int appId) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(ONLINE_PREFIX + appId + ":" + userId));
    }

    /**
     * 设置用户在线状态
     *
     * @param userId 用户ID
     * @param appId  应用ID
     */
    public void setUserOnline(long userId, int appId) {
        redisTemplate.opsForValue().set(ONLINE_PREFIX + appId + ":" + userId, true);
    }

    /**
     * 设置用户离线状态
     *
     * @param userId 用户ID
     * @param appId  应用ID
     */
    public void setUserOffline(long userId, int appId) {
        redisTemplate.delete(ONLINE_PREFIX + appId + ":" + userId);
    }
}